package com.woniu.tms.manage.controller;

import com.woniu.tms.entity.Permission;
import com.woniu.tms.manage.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("manage/permission")
public class PeremissionController {

    @Autowired
    PermissionService permissionService;

    /**
     * 跳转权限列表首页
     *
     * @return
     */
    @RequestMapping("index")
    public String index() {
        return "WEB-INF/manage/permission/index";
    }

    /**
     * 分配权限
     *
     * @param rid
     * @param model
     * @return
     */
    @RequestMapping("assignPermission")
    public String assignPermission(Integer rid, Model model) {
        model.addAttribute("rid", rid);
        return "WEB-INF/manage/permission/assignPermission";
    }

    /**
     * 展示权限树
     *
     * @return
     */
    @RequestMapping("assignPermissionShow")
    @ResponseBody
    public List<Permission> assignPermissionShow() {
        return permissionService.list();
    }

    /**
     * 删除权限
     *
     * @param pid
     * @return
     */
    @RequestMapping("delete")
    @ResponseBody
    public Map<String, Object> delete(Integer pid) {
        Map<String, Object> map = new HashMap<>();
        try {
            permissionService.delete(pid);
            map.put("result", true);
        } catch (Exception e) {
            map.put("result", false);
        }
        return map;
    }

    /**
     * 更新名称
     *
     * @param pid
     * @param name
     * @return
     */
    @RequestMapping("update")
    @ResponseBody
    public Map<String, Object> update(Integer pid, String name) {
        Map<String, Object> map = new HashMap<>();
        try {
            permissionService.update(pid, name);
            map.put("result", true);
        } catch (Exception e) {
            map.put("result", false);
        }
        return map;
    }

    /**
     * 增加权限
     *
     * @param pid
     * @param name
     * @return
     */
    @RequestMapping("add")
    @ResponseBody
    public Map<String, Object> add(Integer pid, String name) {
        Map<String, Object> map = new HashMap<>();
        try {
            permissionService.add(pid, name);
            map.put("result", true);
        } catch (Exception e) {
            map.put("result", false);
        }
        return map;
    }

}
